import { Action } from 'uokay'
import axios from 'axios'
export default class LoginAction extends Action{
    login (okay, event, pipe) {
        return new Promise((resolve, reject) => {
            axios.post('/users/login',{
                username: okay.data.username,
                password: okay.data.password
            }).then(response => {
                pipe.set('response',response)
                resolve('success')
            }).catch(error => {
                pipe.set('error',error)
                reject('fail')
            })
        })
    }
    success (okay, event, pipe) {
        let response = pipe.get('response')
        let code = response.data.code
        console.log(response)
        if (code == 2000) {
            pipe.set('user',response.data.data)
            pipe.delete('response')
            return 'profile'
        }else {
            alert(response.data.msg)
        }
    }
    fail (okay, event, pipe) {
        let response = pipe.get('response')
        alert(response.data.msg)
    }
    register (okay, event, pipe) {
        return new Promise((resolve, reject) => {
            axios.post('/users/register',{
                username: okay.data.username,
                nickname: okay.data.nickname,
                password: okay.data.password
            }).then(response => {
                pipe.set('response', response)
                resolve('success')
            }).catch(error => {
                pipe.set('error',error)
                reject('fail')
            })
        })
    }
    reg_success (okay, event, pipe) {
        let response = pipe.get('response')
        if (response.data.code == 2000) {
            okay.go('/login')
        }else {
            alert(response.data.code + ':' + response.data.msg)
        }
    }
    reg_fail (okay, event, pipe) {
        let error = pipe.get('error')
        alert(error)
    }
}